package com.niannian.activity;

import java.io.File;
import java.util.Date;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.niannian.BaseActivity;
import com.niannian.MyApplication;
import com.niannian.R;
import com.niannian.util.Common;
import com.niannian.util.MyTextWatcher;
import com.niannian.util.PlayerManager;
import com.niannian.util.RecordManager;
import com.niannian.util.VAR;

/**
 * 发布评论
 * 
 * @author shenglin
 * 
 */
public class PushCommentActivity extends BaseActivity {

	public static final int RECORDING = 1;
	RelativeLayout rl_recording;
	ImageView iv_volume_show;
	Button btn_comment_is_recording, btn_comment_is_info, btn_comment_send, btn_comment_recording, btn_comment_recording_play, btn_comment_recording_delete;
	EditText et_comment_info;
	TextView tv_recording_tip;
	LinearLayout ll_is_recording;
	public static PushCommentActivity instance;

	int fid = 0;// 家庭动态ID
	int reply_to = 0;// 被评论人ID
	String reply_to_nickname = "";// 被评论人名字

	String info = "";// 评论文字
	String aud = "";// 评论语音保存地址
	int aud_len1 = 0;// 评论语音长度

	Boolean isaud = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
		setContentView(R.layout.activity_push_comment);

		initView();
		setLister();
		listenerTime();
		initInfo();
		instance = this;
		initData();
	}

	private void initView() {
		rl_recording = (RelativeLayout) findViewById(R.id.rl_recording);
		iv_volume_show = (ImageView) findViewById(R.id.iv_volume_show);
		btn_comment_is_recording = (Button) findViewById(R.id.btn_comment_is_recording);
		btn_comment_is_info = (Button) findViewById(R.id.btn_comment_is_info);
		et_comment_info = (EditText) findViewById(R.id.et_comment_info);
		btn_comment_send = (Button) findViewById(R.id.btn_comment_send);
		tv_recording_tip = (TextView) findViewById(R.id.tv_recording_tip);
		btn_comment_recording = (Button) findViewById(R.id.btn_comment_recording);
		btn_comment_recording_play = (Button) findViewById(R.id.btn_comment_recording_play);
		btn_comment_recording_delete = (Button) findViewById(R.id.btn_comment_recording_delete);

		ll_is_recording = (LinearLayout) findViewById(R.id.ll_is_recording);
		et_comment_info.addTextChangedListener(textWatcher);
		PlayerManager.getAudioPlayer(instance).playerPause();

		et_comment_info.setFocusable(true);
		et_comment_info.setFocusableInTouchMode(true);
		et_comment_info.requestFocus();

	}

	private void setLister() {

		btn_comment_is_recording.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (savePath.length() > 0) {
					initRecordingEnd();
				} else {
					initRecording();
				}

				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(et_comment_info.getWindowToken(), 0); // 强制隐藏键盘
				PlayerManager.getAudioPlayer(instance).playerPause();
			}
		});
		btn_comment_is_info.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				initInfo();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.showSoftInput(et_comment_info, InputMethodManager.SHOW_FORCED);

			}
		});
		btn_comment_recording.setOnTouchListener(new OnTouchListener() {

			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View arg0, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN && !isRecord) {

					if (System.currentTimeMillis() - VAR.ExitTime > VAR.rINTERVAL) {
						btn_comment_recording.setBackgroundResource(R.drawable.recording_pre);
						startRecord();
						VAR.ExitTime = System.currentTimeMillis();
						isRecord = true;
						rm.setIsRStatus(true);
					}
				} else if (event.getAction() == MotionEvent.ACTION_UP && isRecord) {
					VAR.ExitTime = System.currentTimeMillis();
					btn_comment_recording.setBackgroundResource(R.drawable.recording);
					rm.setIsRStatus(false);
					if (timeCount > 0) {
						initRecordingEnd();
					} else {
						initRecording();
					}
					isRecord = false;
					// PlayerManager.getAudioPlayer(instance).PushCommentAud(btn_comment_recording_play,
					// savePath);
				}
				return true;
			}
		});
		btn_comment_recording_delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				PlayerManager.getAudioPlayer(instance).playerPause();
				savePath = "";
				initRecording();
			}
		});

		ll_is_recording.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				info = "";
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(et_comment_info.getWindowToken(), 0); // 强制隐藏键盘
				Bundle pBundle = new Bundle();
				pBundle.putInt("from", RecordActivity.FROM_COMMENT);
				openActivity(RecordActivity.class, pBundle, RECORDING);
				startAnimationLeftToRight();
			}
		});

		btn_comment_send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				info = et_comment_info.getText().toString().trim();
				if (!Common.empty(info)) {
					savePath = "";
					timeCount = 0;
				} else {
					Common.tip(instance, "请输入评论内容");
					return;
				}
				send();
			}
		});
	}

	private void initData() {
		fid = getIntent().getIntExtra("fid", 0);
		try {
			reply_to = getIntent().getIntExtra("reply_to", 0);
			reply_to_nickname = getIntent().getStringExtra("reply_to_nickname");
			if (reply_to > 0) {
				et_comment_info.setHint("回复" + reply_to_nickname + ":");
			}

			if (fid == VAR.pushCommentCache.getFid()) {
				savePath = VAR.pushCommentCache.getAud();
				et_comment_info.setText(VAR.pushCommentCache.getInfo());
				et_comment_info.setSelection(VAR.pushCommentCache.getInfo().length());
				timeCount = VAR.pushCommentCache.getAud_len();
				// PlayerManager.getAudioPlayer(instance).PushCommentAud(btn_comment_recording_play,
				// savePath);
			}

		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	private MyTextWatcher textWatcher = new MyTextWatcher() {

		@Override
		public void onFocusChange(View view, boolean hasFocus) {
		};

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			info = et_comment_info.getText().toString().trim();
			if (!Common.empty(info)) {
				btn_comment_send.setVisibility(View.VISIBLE);
				ll_is_recording.setVisibility(View.GONE);
			} else {
				btn_comment_send.setVisibility(View.GONE);
				ll_is_recording.setVisibility(View.VISIBLE);
			}
		}
	};

	private void send() {

		Intent intent = new Intent();

		intent.putExtra("fid", fid);
		intent.putExtra("reply_to", reply_to);
		intent.putExtra("reply_to_nickname", reply_to_nickname);
		intent.putExtra("info", info);
		intent.putExtra("aud", savePath);
		intent.putExtra("aud_len", timeCount);

		setResult(RESULT_OK, intent);
		PlayerManager.getAudioPlayer(instance).playerPause();
		finish();
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(et_comment_info.getWindowToken(), 0); // 强制隐藏键盘

		VAR.pushCommentCache.setAud("");
		VAR.pushCommentCache.setFid(0);
		VAR.pushCommentCache.setInfo("");
		VAR.pushCommentCache.setAud_len(0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK) {
			return;
		}
		switch (requestCode) {
		case RECORDING:
			savePath = data.getStringExtra("savePath");
			timeCount = data.getIntExtra("time", 0);
			send();
			break;

		default:
			break;
		}
	}

	private void initInfo() {
		isaud = false;
		rl_recording.setVisibility(View.GONE);
		btn_comment_is_info.setVisibility(View.GONE);
		tv_recording_tip.setVisibility(View.GONE);
		btn_comment_recording.setVisibility(View.GONE);

		btn_comment_recording_play.setVisibility(View.GONE);
		btn_comment_recording_delete.setVisibility(View.GONE);

		et_comment_info.setVisibility(View.VISIBLE);
		btn_comment_is_recording.setVisibility(View.GONE);
	}

	private void initRecording() {
		isaud = false;
		rl_recording.setVisibility(View.VISIBLE);
		btn_comment_is_info.setVisibility(View.VISIBLE);
		tv_recording_tip.setVisibility(View.VISIBLE);
		btn_comment_recording.setVisibility(View.VISIBLE);

		btn_comment_recording_play.setVisibility(View.GONE);
		btn_comment_recording_delete.setVisibility(View.GONE);

		et_comment_info.setVisibility(View.GONE);
		btn_comment_is_recording.setVisibility(View.GONE);

		tv_recording_tip.setText("");
	}

	private void initRecordingEnd() {
		isaud = true;
		rl_recording.setVisibility(View.GONE);
		btn_comment_is_info.setVisibility(View.VISIBLE);
		tv_recording_tip.setVisibility(View.VISIBLE);
		btn_comment_recording.setVisibility(View.GONE);

		btn_comment_recording_play.setVisibility(View.VISIBLE);
		btn_comment_recording_delete.setVisibility(View.VISIBLE);

		et_comment_info.setVisibility(View.GONE);
		btn_comment_is_recording.setVisibility(View.GONE);
	}

	RecordManager rm;
	String savePath = "";// 语音路径
	Boolean isRecord = false;

	private void startRecord() {
		PlayerManager.getAudioPlayer(this).playerPause();

		timeCount = 0;
		savePath = MyApplication.FILE_PATH_TEMP + ((new Date()).getTime() / 1000) + ".amr";
		File file = new File(savePath);
		rm.setSavePath(file);
		rm.startRecord();
	}

	Handler timeHandler;
	private int timeCount = 0;
	private int MaxTime = 60;
	private int showTime = 30;

	private void listenerTime() {
		timeHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					timeCount++;
					if ((MaxTime - timeCount) < showTime) {
						tv_recording_tip.setText(Common.showAudLen(timeCount) + "\n(还能说" + (MaxTime - timeCount) + "秒)");
					} else {
						tv_recording_tip.setText(Common.showAudLen(timeCount));
					}

					if (timeCount >= MaxTime) {
						rm.stopRecord();
						initRecordingEnd();
					}
					break;
				case 2:
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(et_comment_info.getWindowToken(), 0); // 强制隐藏键盘
					break;
				case 3:
					InputMethodManager imm1 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm1.showSoftInput(et_comment_info, InputMethodManager.SHOW_FORCED);
					break;
				}
				super.handleMessage(msg);
			}
		};
		rm = new RecordManager(iv_volume_show);
		rm.listenerTime(timeHandler);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		info = et_comment_info.getText().toString().trim();
		VAR.pushCommentCache.setAud(savePath);
		VAR.pushCommentCache.setFid(fid);
		VAR.pushCommentCache.setInfo(info);
		VAR.pushCommentCache.setAud_len(timeCount);
		finish();
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(et_comment_info.getWindowToken(), 0); //
		PlayerManager.getAudioPlayer(instance).playerPause();
		return true;
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		info = et_comment_info.getText().toString().trim();
		VAR.pushCommentCache.setAud(savePath);
		VAR.pushCommentCache.setFid(fid);
		VAR.pushCommentCache.setInfo(info);
		VAR.pushCommentCache.setAud_len(timeCount);
		PlayerManager.getAudioPlayer(instance).playerPause();
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		// TODO Auto-generated method stub
		super.onWindowFocusChanged(hasFocus);
		if (hasFocus) {
			timeHandler.sendEmptyMessageDelayed(2, 100);
			timeHandler.sendEmptyMessageDelayed(3, 200);
		}

	}

}
